$(document).ready(function () {
    validateUser();
});

var ipAddress="localhost";
//验证用户是否登录
var validateUser=function(){
    layer.msg("okk")
    $.ajax({
        //url: "http://" + ipAddress + ":8080/user/get_user_info",
        url: "http://"+ipAddress+":8004/orderInfo/checkAccount",
        type: "GET",
        async: true,
        data: null,
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            console.log(" data====  " + data);
            if (data.message =="success") {
                getOrderPayInfo();
            }else{
                layer.msg("请先登录！");
                setTimeout(function(){//1秒后跳转
                    window.location.href = "./login.html"
                },1000);
            }
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    })
};

var orderProducts = new Array();

//加载页面信息
var getOrderPayInfo=function(){
    $.ajax({
        //url: "http://" + ipAddress + ":8080/user/get_user_info",
        url: "http://" + ipAddress + ":8004/orderInfo/queryLatestOrder",
        type: "GET",
        async: true,
        data: null,
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            console.log(" data====  " + data);
            if (data.success ==true) {
                layer.msg("成功！");

                //应付金额
                $("#duePay").html(data.data.orderInfo.totalMerchandise+data.data.orderInfo.transferFee)

                //收货人姓名
                $("span[name='receiptName']").html(data.data.receipt.name)
                $.each($("span[name='receiptName']"),function (index,value) {
                    $(value).html(data.data.receipt.name);
                });

                //收货人联系电话
                $.each($("span[name='receiptPhone']"),function (index,value) {
                    $(value).html(data.data.receipt.phone);
                });

                //收货人地址
                $.each($("span[name='receiptAddress']"),function (index,value) {
                    $(value).html(data.data.receipt.address);
                });

                //订单号
                $("#orderNo").html(data.data.orderInfo.orderNo);

                //商品信息
                $.each(data.data.orderProductList, function (index, value) {
                    orderProducts.push(value.goodsName);

                    $("#orderProduct").append(value.goodsName+" &nbsp; &nbsp;&nbsp;  "+value.goodsPrice+"元 &nbsp;&nbsp;&nbsp; × &nbsp;&nbsp;&nbsp;"+value.goodsNumber+"<br>");
                });

                //备注信息
                $("#remark").html(data.data.orderInfo.remark);

                var orderTime=new Date(data.data.orderInfo.orderTime);
                //new Date(new Date().getTime() - 1 * 60 * 60 * 1000), new Date();
                var timeoutMinutes=30;
                var endTime=new Date(orderTime.getTime() +  timeoutMinutes * 60 * 1000);
                var nowTime=new Date();
                var time=endTime.getTime()-nowTime.getTime();
                var count=time/1000;
                console.log("endtime=="+endTime);
                console.log("data.data.orderInfo====   "+data.data.orderInfo.orderTime);
                console.log("orderTime====   "+orderTime+"  nowTime====  "+nowTime);
                if (count<0||count==0){
                    closeOrder();
                }else{
                    // //设置时间
                    var intDiff = parseInt(count);//倒计时总秒数量
                    timer(intDiff);
                }
            }else{
                if (data.message=="请先登录！") {
                    layer.msg("请先登录！");
                    setTimeout(function(){//1秒后跳转
                        window.location.href = "./login.html"
                    },2000);
                }else{
                    layer.msg(""+data.message);
                }

            }
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    })

}

//定时器
var timer=function(intDiff){
    window.setInterval(function(){
        var day=0,
            hour=0,
            minute=0,
            second=0;//时间默认值
        if(intDiff > 0){
            day = Math.floor(intDiff / (60 * 60 * 24));
            hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
            minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
        }
        if (minute <= 9) minute = '0' + minute;
        if (second <= 9) second = '0' + second;
        $("#hour_show").html('<s id="h"></s>'+hour+'时');
        $("#minute_show").html('<s></s>'+minute+'分');
        $("#second_show").html('<s></s>'+second+'秒');
        intDiff--;
        if (intDiff==60) {
            layer.msg("订单将在1分钟后失效，请尽快付款哦！")
        }
        if (intDiff==0) {
            closeOrder();
        }
        //console.log("intDiff=="+intDiff);
    }, 1000);
}

var orderNo="";

$(document).on('click', '#alipay-btn', function() {

    orderNo = $("#orderNo").html();
    var duePay = $("#duePay").html();

    layer.open({
        type:1,
        skin: 'layui-layer-rim', //加上边框
        area: ['420px', '240px'], //宽高
        content:'<div class="modal fade modal-hide modal-pay-tip in" id="J_payTip" aria-hidden="false" style="display: block;">\n' +
    '    <div class="modal-header">\n' +
    '        <h3>正在支付...</h3>\n' +
    '        <a class="close" data-dismiss="modal" href="javascript: void(0);"><i class="iconfont"></i></a>\n' +
    '    </div>\n' +
    '    <div class="modal-body clearfix">\n' +
    '        <div class="success">\n' +
    '            <h4>支付成功了</h4>\n' +
    '            <p><a onclick="updateStatus()">立即查看订单详情 &gt;</a></p>\n' +
    '            <p><a onclick="downloadPayDetail()">下载支付信息 &gt;</a></p>\n' +
    '        </div>\n' +
    '        <div class="fail">\n' +
    '            <h4>如果支付失败</h4>\n' +
    '            <p><a href="http://bbs.xiaomi.cn/thread/index/tid/11544653" target="_blank" data-stat-id="b79f1fe5cccf37af" onclick="_msq.push([\'trackEvent\', \'f1542ececd0b6bc5-b79f1fe5cccf37af\', \'http://bbs.xiaomi.cn/thread/index/tid/11544653\', \'pcpid\', \'\']);">查看支付常见问题 &gt;</a></p>\n' +
    '        </div>\n' +
    '    </div>\n' +
    '</div>'
    })


    var URL = "http://" + ipAddress + ":8005/alipay/pcPay/"+orderNo+"/"+orderProducts+"/"+duePay;

    window.open(URL);



})

var downloadPayDetail = function () {


    $.ajax({
        url: "http://" + ipAddress + ":8005/orderPayHistory/downloadPayDetail/"+orderNo,
        type: "GET",
        async: true,
        data: null,
        dataType: "json",
        success: function (data) {
            layer.msg("下载成功，已保存在桌面上！")
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    })

}


var updateStatus = function () {

    var out_trade_no = orderNo;

    $.ajax({
        url: "http://" + ipAddress + ":8005/alipay/tradeQueryByStr/"+out_trade_no,
        type: "GET",
        async: true,
        data: null,
        dataType: "json",
        success: function (data) {
            window.location.href="./orderDetail.html?orderNo="+orderNo;
            layer.msg("ok")
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    })

}



//关闭订单
var closeOrder= function () {
    var orderInfo={
        orderNo:$("#orderNo").html(),
        orderStatus:5
    };
    console.log("orderInfo=====gggggg========="+orderInfo);
    layer.msg("订单将关闭");
    $.ajax({
        //url: "http://" + ipAddress + ":8080/user/get_user_info",
        url: "http://"+ipAddress+":8004/orderInfo/updateStatusByOrderNo",
        type: "PUT",
        async: true,
        data: JSON.stringify(orderInfo),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            console.log(" data====  " + data);
            if (data.success ==true) {
                $("#title").html("该订单已失效！");
                setTimeout(function(){//2秒后跳转
                    window.location.href = "./index.html"
                },2000);
            }else{
                layer.msg("请先登录！");
                setTimeout(function(){//1秒后跳转
                    window.location.href = "./login.html"
                },1000);
            }
        },
        error: function () {
            layer.msg("后台服务器开小差了...")
        }
    });
};






















